<template>
  <form-dialog
    ref="formDrawerRef"
    top="2vh"
    width="98%"
    :destroyOnClose="true"
    :title="drawerTitle"
    @submit="handleSubmit"
  >
    <div class="dialog-body">
      <el-form ref="formRef" :model="form" :rules="rules" label-position="top">
        <el-row :gutter="20">
          <template v-for="item in formConfigList" :key="item.prop">
            <template v-if="item.types === 'input'">
              <el-col
                v-if="item.showLabel && item.showValue.includes(form[item.showLabel])"
                :span="item.span"
                ><el-form-item :label="item.label" :prop="item.prop">
                  <el-input
                    v-model="form[item.prop as any]"
                    :type="item.type"
                    :min="item.min"
                    :maxlength="item.maxlength"
                    :placeholder="item.placeholder"
                    :disabled="item.disabled"
                    ><template #append v-if="item.unit">{{ item.unit }}</template></el-input
                  ></el-form-item
                ></el-col
              >
              <el-col v-if="!item.showLabel" :span="item.span">
                <el-form-item :label="item.label" :prop="item.prop">
                  <el-input
                    v-model="form[item.prop as any]"
                    :type="item.type"
                    :min="item.min"
                    :maxlength="item.maxlength"
                    :placeholder="item.placeholder"
                    :disabled="item.disabled"
                    ><template #append v-if="item.unit">{{ item.unit }}</template></el-input
                  >
                </el-form-item>
              </el-col>
            </template>
            <template v-else-if="item.types === 'select'">
              <el-col :span="item.span">
                <el-form-item :label="item.label" :prop="item.prop">
                  <el-select
                    v-model="form[item.prop as any]"
                    :placeholder="item.placeholder"
                    :disabled="item.disabled"
                    filterable
                  >
                    <el-option
                      v-for="option in item.options"
                      :key="option.value"
                      :label="option.label"
                      :value="option.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </template>
            <template v-else-if="item.types === 'date'">
              <el-col
                v-if="item.showLabel && item.showValue.includes(form[item.showLabel])"
                :span="item.span"
              >
                <el-form-item :label="item.label" :prop="item.prop">
                  <el-date-picker
                    v-model="form[item.prop as any]"
                    :type="item.type"
                    :placeholder="item.placeholder"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    :disabled="item.disabled"
                    :disabled-date="item.disabledTime"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col v-if="!item.showLabel" :span="item.span">
                <el-form-item :label="item.label" :prop="item.prop">
                  <el-date-picker
                    v-model="form[item.prop as any]"
                    :type="item.type"
                    :placeholder="item.placeholder"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    :disabled="item.disabled"
                    :disabled-date="item.disabledTime"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </template>
          </template>
        </el-row>
      </el-form>
    </div>
  </form-dialog>
</template>
<script setup lang="ts">
import { onMounted, ref, watch } from "vue";
import { useInitForm } from "@/hooks/useCommon";
import FormDialog from "@/components/FormDialog.vue";
import { colorTypeList, carStatusList, energyTypeList, carCategoryList } from "@/enum/index";
import { isCarNum, isIntegerNumber } from "@/utils/regular";
import { addEnterpriseCarApi, editEnterpriseCarApi } from "@/api/second";
import { getAreaListApi } from "@/api/user";

const emits = defineEmits(["success"]);
// 新增或编辑车辆
const { formDrawerRef, formRef, drawerTitle, form, rules, handleCreate, handleEdit, handleSubmit } =
  useInitForm({
    form: {
      id: "",
      licensePlateColor: "",
      licensePlate: "",
      vehicleModel: "",
      carCategory: "",
      carType: "",
      engineType: "",
      vin: "",
      carRegisterPlaceCode: "",
      businessStatus: "",
      registerDate: "",
      energyType: "",
      maintainPlan: "",
      maintainPlanValue: "",
      policyExpirationTime: ""
    },
    rules: {
      licensePlateColor: [{ required: true, message: "请选择车牌颜色", trigger: "change" }],
      licensePlate: [
        { required: true, message: "请输入车牌号", trigger: "blur" },
        {
          validator(rule: any, value: any, callback: any) {
            if (!isCarNum(value)) {
              callback(new Error("请输入正确的车牌号"));
            } else {
              callback();
            }
          }
        }
      ],
      vehicleModel: [{ required: true, message: "请输入车辆品牌", trigger: "blur" }],
      carCategory: [{ required: true, message: "请选择车辆类别", trigger: "change" }],
      carType: [{ required: true, message: "请选择车辆类型", trigger: "change" }],
      engineType: [{ required: true, message: "请输入发动机型号", trigger: "blur" }],
      vin: [
        { required: true, message: "请输入车架号", trigger: "blur" },
        {
          validator(rule: any, value: any, callback: any) {
            if (!/^[A-Za-z0-9]{17}$/.test(value)) {
              callback(new Error("请输入正确的车架号"));
            } else {
              callback();
            }
          }
        }
      ],
      carRegisterPlaceCode: [{ required: true, message: "请选择车籍地", trigger: "change" }],
      businessStatus: [{ required: true, message: "请选择营运状态", trigger: "change" }],
      registerDate: [{ required: true, message: "请选择注册日期", trigger: "change" }],
      energyType: [{ required: true, message: "请选择燃料类型", trigger: "change" }],
      maintainPlan: [{ required: true, message: "请选择维修计划", trigger: "change" }],
      maintainPlanValue: [
        { required: true, message: "请输入维修计划", trigger: "blur" },
        {
          validator(rule: any, value: any, callback: any) {
            if (!isIntegerNumber(value)) {
              callback(new Error("请输入正整数"));
            } else {
              callback();
            }
          }
        }
      ],
      policyExpirationTime: [
        { required: true, message: "请选择承运人责任保险到期时间", trigger: "change" }
      ]
    },
    createData: addEnterpriseCarApi,
    updateData: editEnterpriseCarApi,
    success: () => {
      emits("success");
    }
  });

const formConfigList = ref([
  {
    types: "select",
    span: 6,
    label: "车牌颜色",
    prop: "licensePlateColor",
    placeholder: "请选择车牌颜色",
    options: colorTypeList,
    disabled: false
  },
  {
    types: "input",
    span: 6,
    label: "车牌号",
    prop: "licensePlate",
    placeholder: "请输入车牌号",
    type: "text",
    maxlength: 10,
    min: 1,
    disabled: false
  },
  {
    types: "input",
    span: 6,
    label: "车辆品牌",
    prop: "vehicleModel",
    placeholder: "请输入车辆品牌",
    type: "text",
    maxlength: 10,
    min: 1,
    disabled: false
  },
  {
    types: "select",
    span: 6,
    label: "车辆类别",
    prop: "carCategory",
    placeholder: "请选择车辆类别",
    options: carCategoryList,
    disabled: false
  },
  {
    types: "select",
    span: 6,
    label: "车辆类型",
    prop: "carType",
    placeholder: "请先选择车辆类别",
    options: [],
    disabled: true
  },
  {
    types: "input",
    span: 6,
    label: "发动机型号",
    prop: "engineType",
    placeholder: "请输入发动机型号",
    type: "text",
    maxlength: 20,
    min: 1,
    disabled: false
  },
  {
    types: "input",
    span: 6,
    label: "底盘(车身)号",
    prop: "vin",
    placeholder: "请输入底盘(车身)号",
    type: "text",
    maxlength: 20,
    min: 1,
    disabled: false
  },
  {
    types: "select",
    span: 6,
    label: "车籍地",
    prop: "carRegisterPlaceCode",
    placeholder: "请选择车籍地",
    options: [],
    disabled: false
  },
  {
    types: "select",
    span: 6,
    label: "营运状态",
    prop: "businessStatus",
    placeholder: "请选择营运状态",
    options: carStatusList,
    disabled: false
  },
  {
    types: "date",
    span: 6,
    label: "上牌时间",
    prop: "registerDate",
    placeholder: "请选择上牌时间",
    type: "date",
    disabled: false,
    disabledTime: (time: any) => {
      return time.getTime() > Date.now();
    }
  },
  {
    types: "select",
    span: 6,
    label: "燃料类型",
    prop: "energyType",
    placeholder: "请选择燃料类型",
    options: energyTypeList,
    disabled: false
  },
  {
    types: "select",
    span: 6,
    label: "维护计划",
    prop: "maintainPlan",
    placeholder: "请选择维护计划",
    options: [
      {
        label: "公里数",
        value: 1
      },
      {
        label: "天数",
        value: 2
      }
    ],
    disabled: false
  },
  {
    types: "input",
    span: 6,
    label: "维护公里数",
    prop: "maintainPlanValue",
    placeholder: "请输入维护公里数",
    type: "number",
    min: 1,
    maxlength: 5,
    disabled: false,
    unit: "KM",
    showLabel: "maintainPlan",
    showValue: [1]
  },
  {
    types: "input",
    span: 6,
    label: "维护天数",
    prop: "maintainPlanValue",
    placeholder: "请输入维护天数",
    type: "number",
    min: 1,
    maxlength: 5,
    disabled: false,
    unit: "天",
    showLabel: "maintainPlan",
    showValue: [2]
  },
  {
    types: "date",
    span: 8,
    label: "客车、危货承运人责任保险单到期时间",
    prop: "policyExpirationTime",
    placeholder: "请选择客车、危货承运人责任保险单到期时间",
    type: "date",
    disabled: false,
    showLabel: "carCategory",
    showValue: [1, 3]
  }
]);
// 当前日期后面的时间不可选
const handleDisabledDate = (time: any) => {
  return time.getTime() > Date.now();
};
// 根据不同车辆类别显示对应的车辆类型
const handleUpdateCarType = (val: number) => {
  const curItem = carCategoryList.find((item) => item.value === val);
  const newItem = curItem!.options;
  formConfigList.value = formConfigList.value.map((item) => {
    if (item.prop === "carType") {
      item.options = newItem as any;
    }
    return item;
  });
};
// 获取车籍地
const getAreaList = async () => {
  const res: any = await getAreaListApi();
  const newItem = res.map((item: any) => {
    return {
      label: item.area,
      value: item.areaCode
    };
  });
  formConfigList.value = formConfigList.value.map((item) => {
    if (item.prop === "carRegisterPlaceCode") {
      item.options = newItem;
    }
    item.disabled = false;
    return item;
  });
};
onMounted(() => {
  getAreaList();
});
watch(
  () => form.carCategory,
  (val) => {
    if (val) {
      handleUpdateCarType(val);
    } else {
      formConfigList.value = formConfigList.value.map((item) => {
        if (item.prop === "carType") {
          item.options = [];
        }
        return item;
      });
    }
  },
  { immediate: true }
);
defineExpose({
  handleCreate,
  handleEdit
});
</script>
<style scoped lang="scss">
.dialog-body {
  height: calc(100vh - 200px);
  overflow-y: auto;
  overflow-x: hidden;
}
</style>
